package com.smallcc.controller;

import com.mysql.fabric.xmlrpc.base.Data;
import com.smallcc.dataobject.ProductCategory;
import com.smallcc.dataobject.ProductInfo;
import com.smallcc.service.CategoryService;
import com.smallcc.service.ProductService;
import com.smallcc.util.ResultVoUtil;
import com.smallcc.vo.ProductInfoVO;
import com.smallcc.vo.ProductVO;
import com.smallcc.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author 晓风过境
 * @买家商城访问控制
 * @date 2018/3/28 22:20
 * @day 28
 * @return $text$
 * @title ${CLASS_NAME}
 * @project_name sell
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {
    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    //@GetMapping("/list")等同与
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @Cacheable(cacheNames = "product",key = "#sellerId",condition = "#sellerId.length()>3" , unless = "#reslut.getCode()!=0")
    public ResultVO list(String sellerId) {
    //1. 查询所有的上架商品
            List<ProductInfo> productInfoList = productService.findUpAll();

    //2. 查询类目(一次性查询)
//        List<Integer> categoryTypeList = new ArrayList<>();
    //传统方法
//        for (ProductInfo productInfo : productInfoList) {
//            categoryTypeList.add(productInfo.getCategoryType());
//        }
    //精简方法(java8, lambda)
    List<Integer> categoryTypeList = productInfoList.stream()
            .map(e -> e.getCategoryType())
            .collect(Collectors.toList());
    List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList);

    //3. 数据拼装
    List<ProductVO> productVOList = new ArrayList<>();
        for (ProductCategory productCategory: productCategoryList) {
        ProductVO productVO = new ProductVO();
        productVO.setCategoryType(productCategory.getCategoryType());
        productVO.setCategoryName(productCategory.getCategoryName());

        List<ProductInfoVO> productInfoVOList = new ArrayList<>();
        for (ProductInfo productInfo: productInfoList) {
            if (productInfo.getCategoryType().equals(productCategory.getCategoryType())) {
                ProductInfoVO productInfoVO = new ProductInfoVO();
                BeanUtils.copyProperties(productInfo, productInfoVO);
                productInfoVOList.add(productInfoVO);
            }
        }
        productVO.setProductInfoVOList(productInfoVOList);
        productVOList.add(productVO);
    }

        return ResultVoUtil.sucess(productVOList);
}
}
